package cn.wolfcode.exception;

import cn.hutool.db.Session;
import cn.wolfcode.domain.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@ControllerAdvice
public class MyControllerAdvice {
    private static int NUM = 3;

    @ExceptionHandler(RuntimeException.class)
    //@ResponseBody
    public String handler(RuntimeException e, HandlerMethod method, HttpServletResponse response){
        e.printStackTrace();
        //判断控制器方法是否贴有ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            try {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSON.toJSONString(new JsonResult(false,"系统有误,请稍后再试")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return null;
        }
        return "common/error";
    }

    @ExceptionHandler(LoginException.class)
    //@ResponseBody
    public String handler(LoginException e, HandlerMethod method, HttpServletRequest req, HttpServletResponse response){
        e.printStackTrace();
        //判断控制器方法是否贴有ResponseBody注解
        if (method.hasMethodAnnotation(ResponseBody.class)) {
            try {
                if(NUM>0){
                    NUM = NUM-1;
                }else {
                    HttpSession session = req.getSession();
                    session.setAttribute("num",NUM);
                    session.setMaxInactiveInterval(1000*100);
                }
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSON.toJSONString(new JsonResult(false,e.getMessage()+",还有"+NUM+"次机会")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return null;
        }

        return "common/error";
    }
}
